from tools import DefaultDict

def get_all_subseqs(seq, length):
    subseqs = list()
    for i in range(len(seq) - length + 1):
        subseqs.append(seq[i:i+length])
    return subseqs


class NGram(object):
    def __init__(self, n, seq=None):
        self.n = n
        self._dict = DefaultDict(default=0)
        if seq:
            self.update(seq)

    def update(self, seq):
        subseqs = get_all_subseqs(seq, length=n)
        for subseq in subseqs:
            self._dict[subseq] += 1

    def __getitem__(self, key):
        return self._dict.__getitem__(key)
